<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Utils\ModelOperatorTrait;
use App\Rules\CarNumberRule;
use App\Rules\IdCardRule;
use App\Rules\PhoneRule;
use Illuminate\Validation\Rule;

class InternalVehicleController extends Controller
{
    use ModelOperatorTrait;

    protected function model(){
        return app(\App\Models\InternalVehicle::class);
    }

    protected function getAttributes(){
        return [
            'print_code' => '印刷编号',
            'ic_id' => 'IC卡号（0扇区0块）',
            'vehicle_number' => '车牌号',
            'driver_name' => '司机姓名',
            'driver_idcard' => '司机身份证',
            'driver_mobile_phone' => '司机号码',
            'tare' => '车辆皮重（kg）',
            'update_datetime' => '更新时间',
            'operator' => '操作人员',
            'remarks' => '备注'
        ];
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $internalVehicle = $this->queryModel(request()->input(),['weightdata']);

        if(request()->has('page')){
            $pageSize = 10;
            if(request()->has('pageSize')){
                $pageSize = request()->pageSize;
            }
            $internalVehicle = $internalVehicle->paginate($pageSize);
        }
        else{
            $internalVehicle = $internalVehicle->get();
        }

        return formatJsonResponse($internalVehicle);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [
            'print_code' => ['required','unique:internal_vehicle,print_code'],
            'ic_id' => ['required','unique:internal_vehicle,ic_id'],
            'vehicle_number' => ['required',new CarNumberRule()],
            'driver_idcard' => ['nullable',new IdCardRule()],
            'driver_mobile_phone' => ['nullable',new PhoneRule()],
            'tare' => 'required|numeric',
            'operator' => 'required',
            'update_datetime' => 'required'
        ];

        $request->offsetSet('update_datetime',now());

        $request->offsetSet('operator',auth()->user()->nickname);

        $this->validate($rules);

        $this->storeModel($request->all());

        return formatJsonResponse();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return formatJsonResponse($this->findModel($id));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $rules = [
            'print_code' => [
                'required',
                Rule::unique('internal_vehicle','print_code')->where(function ($query) use ($id){
                    $query->where('print_code','<>', $id);
                })
            ],
            'ic_id' => [
                'required',
                Rule::unique('internal_vehicle','ic_id')->where(function ($query) use ($request){
                    $query->where('ic_id','<>', $request->ic_id);
                })
            ],
            'vehicle_number' => ['required',new CarNumberRule()],
            'driver_idcard' => ['nullable',new IdCardRule()],
            'driver_mobile_phone' => ['nullable',new PhoneRule()],
            'tare' => 'required|numeric',
            'update_datetime' => 'required'
        ];

        $request->offsetSet('update_datetime',now());

        $request->offsetSet('operator',auth()->user()->nickname);

        $this->validate($rules);

        $this->updateModel($id,$request->all());

        return formatJsonResponse();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->deleteModel($id);

        return formatJsonResponse();
    }

    public function updateIsVoid($id,Request $request){

        $rules = [
            'is_void' => 'required|in:0,1',
            'empty_type' => 'required|in:0,1,2',
        ];

        $this->validate($rules);

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->is_void = $request->is_void;

            $internalVehicle->empty_type = $request->empty_type;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updateEmptyType($id,Request $request){
        $rules = [
            'empty_type' => 'required|in:0,1',
        ];

        $this->validate($rules);

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->empty_type = $request->empty_type;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updateIsLoading($id,Request $request){
        $rules = [
            'is_loading' => 'required|in:0,1',
        ];

        $this->validate($rules);

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->is_loading = $request->is_loading;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updateIsReturn($id,Request $request){

        $rules = [
            'is_return' => 'required|in:0,1',
        ];

        $this->validate($rules);

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->is_return = $request->is_return;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updateIsGo($id,Request $request){
        $rules = [
            'is_go' => 'required|in:0,1',
        ];

        $this->validate($rules);

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->is_go = $request->is_go;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updatePurchaseWeight($id,Request $request){
        $rules = [
            'purchase_weight' => 'required|numeric',
        ];

        $this->validate($rules);

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->purchase_weight = $request->purchase_weight;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updateDischargeWeight($id,Request $request){
        $rules = [
            'discharge_weight' => 'required|numeric',
        ];

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->discharge_weight = $request->discharge_weight;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updatePickWeight($id,Request $request){
        $rules = [
            'pick_weight' => 'required|numeric',
        ];

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->pick_weight = $request->pick_weight;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }

    public function updateException($id,Request $request){
        $rules = [
            'exception' => 'required',
        ];

        $internalVehicle = $this->findModel($id);

        if(isset($internalVehicle)){
            $internalVehicle->exception = $request->exception;

            $internalVehicle->save();
        }

        return formatJsonResponse();
    }


    public function access(Request $request){

        $conditions = $request->all();

        $conditions['vehicle_type'] = 'IN';

        $weightdata = $this->queryModel($conditions,['internalVehicle'],app(\App\Models\Weighdata::class));

        if(request()->has('page')){
            $weightdata = $weightdata->orderBy('system_datetime','DESC')->paginate();
        }
        else{
            $weightdata = $weightdata->get();
        }

        return formatJsonResponse($weightdata);
    }


    public function success($id){
        $summaryModel = app(\App\Models\Summary::class);

        $internalVehicle = $this->findModel($id,['weightdata']);

        $createData = [
            'vehicle_number' => $internalVehicle->vehicle_number,
            'driver_name' => $internalVehicle->driver_name,
            'tare' => $internalVehicle->tare,
            'empty_type' => $internalVehicle->empty_type,
            'purchase_weight' => $internalVehicle->purchase_weight,
            'discharge_weight' => $internalVehicle->discharge_weight,
            'pick_weight' => $internalVehicle->pick_weight,
            'is_return' => $internalVehicle->is_return,
            'is_go' => $internalVehicle->is_go,
            'exception' => $internalVehicle->exception
        ];

        if(isset($internalVehicle->weightdata)){
            $createData['first_weight'] = $internalVehicle->weightdata->first_weight;

            $createData['empty_weight_time'] = $internalVehicle->weightdata->empty_weight_time;

            $createData['weight_error_ratio'] = $internalVehicle->weightdata->weight_error_ratio;

            $createData['is_void'] = $internalVehicle->weightdata->is_empty;
            
            $createData['net_weight'] = $internalVehicle->weightdata->net_weight;

            $createData['empty_weight'] = $internalVehicle->weightdata->empty_weight;

            $createData['weight_error'] = $internalVehicle->weightdata->weight_error;

            $createData['is_success'] = $internalVehicle->weightdata->is_success;

            $createData['is_finished'] = $internalVehicle->weightdata->is_finished;

            $createData['first_readic_datetime'] = $internalVehicle->weightdata->first_readic_datetime;
        }

        $this->storeModel($createData,$summaryModel);

        $internalVehicle->order_systemnumber = null;

        $internalVehicle->is_void = 0;

        $internalVehicle->empty_type = 2;

        $internalVehicle->is_loading = 0;

        $internalVehicle->purchase_weight = 0;

        $internalVehicle->discharge_weight = 0;

        $internalVehicle->pick_weight = 0;

        $internalVehicle->is_return = 0;

        $internalVehicle->is_go = 0;

        $internalVehicle->exception = null;

        $internalVehicle->save();

        return formatJsonResponse();
    }
}
